from arconn.card.models import *
from django.core.paginator import *
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
import datetime

def get_username(request):
    if request.session.get('userid', False):
        return request.session['userid']
    else:
        return ""

def index(request):
    username = get_username(request)

    if username != "":
        return HttpResponseRedirect("/user/" + username + "/")

    return render_to_response("index.html")
    

def view_card(request, card_name):
    username = get_username(request)

    try:
        card = Card.objects.get(nickname=card_name)
        blink_msg = '(click to add text)'
        if card.name == '':
            card.name = blink_msg
        if card.location == '':
            card.location = blink_msg
        if card.post == '':
            card.post = blink_msg
        if card.email == '':
            card.email = blink_msg
    except Card.DoesNotExist:
        return render_to_response("create.html", {"card_name":card_name})

    if username == card_name:
        mine = True
    else:
        mine = False

    if get_connection_by_name(username, card_name) == None:
        has_story = False
    else:
        has_story = True

    return render_to_response("view.html", {"card_name":card_name, 
                                            "name":card.name,
                                            "location":card.location,
                                            "post":card.post,
                                            "email":card.email,
                                            "username":username,
                                            "mine":mine,
                                            "has_story":has_story,
                                            })

def create_card(request, card_name):
    card = Card(photo='',
                nickname=card_name,
                name='',
                location='',
                post='',
                email='')
    card.save()
    return HttpResponseRedirect("/user/" + card_name + "/")

def edit_card(request, card_name):
    username = get_username(request)

    try:
        card = Card.objects.get(nickname=card_name)
        name = card.name
        location = card.location
        post = card.post
        email = card.email
    except Card.DoesNotExist:
        name = ""
        location = ""
        post = ""
        email = ""
    return render_to_response("edit.html", {"card_name":card_name,
                                            "name":name,
                                            "location":location,
                                            "post":post,
                                            "email":email,
                                            "username":username,
                                            })

def save_card(request, card_name):
    name = request.POST["name"]
    location = request.POST["location"]
    post = request.POST["post"]
    email = request.POST["email"]
    try:
        card = Card.objects.get(nickname=card_name)
        card.name = name
        card.location = location
        card.post = post
        card.email = email
    except Card.DoesNotExist:
        card = Card(nickname=card_name,
                    name = name,
                    location = location,
                    post = post,
                    email = email
                    )
    card.save()
    return HttpResponseRedirect("/user/" + card_name + "/") 

def partial_save_card(request, card_name):
    value = request.POST["content"]
    column = request.POST["pid"]
    try:
        card = Card.objects.get(nickname=card_name)
        card.__dict__[column] = value
    except Card.DoesNotExist:
        card = Card(nickname=card_name,
                    name = name,
                    location = location,
                    post = post,
                    email = email
                    )
    card.save()
    return HttpResponseRedirect("/user/" + card_name + "/")        

def user_xml(request, card_name):
    card = get_object_or_404(Card, nickname=card_name)
    return render_to_response("person.xml", {"card_name":card_name, 
                                             "name":card.name,
                                             "location":card.location,
                                             "post":card.post,
                                             "email":card.email
                                             })

def checkin(request):
    card_name = request.POST['nickname']
    request.session['userid'] = card_name
    try:
        card = Card.objects.get(nickname=card_name)
    except Card.DoesNotExist:
        return render_to_response("create.html", {"card_name":card_name})

    return HttpResponseRedirect('/user/' + card_name)

def logout(request):
    try:
        del request.session['userid']
    except KeyError:
        pass
    return HttpResponseRedirect("/")

def userlist(request):
    username = get_username(request)

    cards = Card.objects.order_by('nickname')
    return render_to_response('userlist.html', {'users': cards,
                                                'username': username,
                                                })

def userlist_xml(request):
    cards = Card.objects.order_by('nickname')
    return render_to_response('people.xml', {'people': cards})

def connect(request, card_name):
    username = get_username(request)
    user = Card.objects.get(nickname=username)
    target = Card.objects.get(nickname=card_name)

    connection = Connection(source=user, target=target)
    connection.save()
    
    url = '/story/' + user.nickname + '+' + target.nickname
    return HttpResponseRedirect(url)
    

def get_connection(user1, user2):
    try:
        connection = Connection.objects.get(source=user1, target=user2)
    except Connection.DoesNotExist:
        try:
            connection = Connection.objects.get(source=user2, target=user1)
        except Connection.DoesNotExist:
            return None

    return connection

def get_connection_by_name(user1, user2):
    source = Card.objects.get(nickname=user1)
    target = Card.objects.get(nickname=user2)

    return get_connection(source.id, target.id)

def story(request, relation):
    username = get_username(request)
    users = relation.split('+')
    user1 = Card.objects.get(nickname=users[0])
    user2 = Card.objects.get(nickname=users[1])
    
    connection = get_connection(user1.id, user2.id)
    try:
        stories = Story.objects.filter(connection=connection)
    except Story.DoesNotExist:
        stories = []
    
    return render_to_response('story.html', {'username': username,
                                             'relation': relation,
                                             'user1': users[0],
                                             'user2': users[1],
                                             'stories' : stories})

def save_story(request, relation):
    user1 = request.POST["user1"]
    user2 = request.POST["user2"]
    when_list = request.POST["when"].split("-")
    when = datetime.date(int(when_list[0]), int(when_list[1]), int(when_list[2]))
    where = request.POST["where"]
    why = request.POST["why"]

    connection = get_connection_by_name(user1, user2)

    story = Story(connection = connection, 
                  when = when, 
                  where = where,
                  why = why
                  )

    story.save()
    return HttpResponseRedirect("/story/" + user1 + "+" + user2 + "/") 
